package news.action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import news.biz.TypesBiz;

/**
 * 新闻类型
 * @author Administrator
 *
 */
@WebServlet("/types.do")
public class TypesAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private TypesBiz typesBiz;
	private HttpSession session ;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		// 实例化session对象
		session = request.getSession();
		// 获取op参数
		String op = request.getParameter("op");
		// 获得方法返回的页面名
		String url = "";
		switch ( op ) {
			case "add":
				url = showAddPage(request,response);
				break;
			case "insert":
				url = addTypes(request,response);
				break;
			default:
				url = "error.jsp";
				break;
		}
		
		// 进行统一跳转
		request.getRequestDispatcher("WEB-INF/pages/" + url).forward(request, response);
	}

	/**
	 * 添加新闻类型
	 * @param request
	 * @param response
	 * @return
	 */
	private String addTypes(HttpServletRequest request, HttpServletResponse response) {
		String title = request.getParameter("title");
		String remark = request.getParameter("remark");
		
		if( typesBiz().addNewsType(title, remark) ) {
			return "manage.jsp?include=welcome.jsp";
		} else {
			request.setAttribute("error", "对不起，添加新闻类型失败，请稍后再试！");
			return "manage.jsp?include=addTypes.jsp";
		}
	}

	/**
	 * 跳转到添加新闻页面
	 * @param request
	 * @param response
	 * @return
	 */
	private String showAddPage(HttpServletRequest request, HttpServletResponse response) {
		return "manage.jsp?include=addTypes.jsp";
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	public TypesBiz typesBiz() {
		if ( typesBiz == null ) {
			typesBiz = new TypesBiz();
		}
		return typesBiz;
	}
}
